import tkinter as tk
from tkinter import ttk, filedialog, messagebox
import datetime
import threading
import time
import pandas as pd
from ttkbootstrap import Style

# 全局变量
stop_event = None
adjustment_thread = None


def adjust_bid(current_bid, max_bid, min_bid, current_time, accumulated_spend, total_budget, standard_spend_ratios):
    """出价调整算法"""
    hour = current_time.hour
    closest_time_key = f"{hour}:00"
    standard_spend_percentage = standard_spend_ratios.get(closest_time_key, 0)
    standard_spend = total_budget * (standard_spend_percentage / 100.0)
    spend_difference = standard_spend - accumulated_spend

    if spend_difference > 0:
        adjustment_direction = 1  # 加价
    elif spend_difference < 0:
        adjustment_direction = -1  # 减价
    else:
        return current_bid

    difference_ratio = abs(spend_difference) / standard_spend if standard_spend > 0 else 0
    adjustment = 0.1 if difference_ratio > 0.1 else 0.05
    new_bid = current_bid + (adjustment_direction * adjustment)
    new_bid = max(min_bid, min(max_bid, new_bid))

    # 记录日志
    log_entry = f"{datetime.datetime.now()} | 当前出价: {current_bid:.2f} | 新出价: {new_bid:.2f} | 差值比例: {difference_ratio:.2%}\n"
    with open("bid_adjustment_log.txt", "a") as f:
        f.write(log_entry)

    return new_bid


def load_excel():
    """导入Excel文件并自动填充数据"""
    filepath = filedialog.askopenfilename(filetypes=[("Excel文件", "*.xlsx *.xls")])
    if not filepath:
        return

    try:
        df = pd.read_excel(filepath)
        if not all(col in df.columns for col in ["当前出价", "最大出价", "最小出价", "总预算", "当前累计消费"]):
            messagebox.showerror("错误", "Excel缺少必要列！请包含：当前出价、最大出价、最小出价、总预算、当前累计消费")
            return

        # 自动填充数据
        entry_current_bid.delete(0, tk.END)
        entry_current_bid.insert(0, df["当前出价"].iloc[0])

        entry_max_bid.delete(0, tk.END)
        entry_max_bid.insert(0, df["最大出价"].iloc[0])

        entry_min_bid.delete(0, tk.END)
        entry_min_bid.insert(0, df["最小出价"].iloc[0])

        entry_total_budget.delete(0, tk.END)
        entry_total_budget.insert(0, df["总预算"].iloc[0])

        entry_accumulated_spend.delete(0, tk.END)
        entry_accumulated_spend.insert(0, df["当前累计消费"].iloc[0])

        messagebox.showinfo("成功", "Excel数据导入完成！")

    except Exception as e:
        messagebox.showerror("错误", f"读取Excel失败:\n{str(e)}")


def start_adjustment():
    """启动自动调整"""
    global stop_event, adjustment_thread

    try:
        current_bid = float(entry_current_bid.get())
        max_bid = float(entry_max_bid.get())
        min_bid = float(entry_min_bid.get())
        total_budget = float(entry_total_budget.get())
        accumulated_spend = float(entry_accumulated_spend.get())
    except ValueError:
        messagebox.showerror("错误", "请输入有效的数字！")
        return

    standard_spend_ratios = {
        "0:00": 0, "1:00": 2, "2:00": 3.5, "3:00": 4.5, "4:00": 5.0,
        "5:00": 5.8, "6:00": 6.8, "7:00": 8, "8:00": 10, "9:00": 12,
        "10:00": 15, "11:00": 20, "12:00": 25, "13:00": 30, "14:00": 36,
        "15:00": 44, "16:00": 51, "17:00": 55, "18:00": 59, "19:00": 65,
        "20:00": 71, "21:00": 78, "22:00": 87, "23:00": 95, "24:00": 100
    }

    def run_periodically():
        while not stop_event.is_set():
            current_time = datetime.datetime.now().time()
            new_bid = adjust_bid(
                current_bid, max_bid, min_bid, current_time,
                accumulated_spend, total_budget, standard_spend_ratios
            )
            result_text.config(state=tk.NORMAL)
            result_text.insert(tk.END,
                               f"{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} - 新出价: {new_bid:.2f}\n")
            result_text.see(tk.END)
            result_text.config(state=tk.DISABLED)
            time.sleep(3600)  # 1小时 = 3600秒

    if adjustment_thread and adjustment_thread.is_alive():
        messagebox.showwarning("警告", "调整程序已在运行中！")
        return

    stop_event = threading.Event()
    adjustment_thread = threading.Thread(target=run_periodically)
    adjustment_thread.daemon = True
    adjustment_thread.start()

    btn_start.config(state=tk.DISABLED)
    btn_stop.config(state=tk.NORMAL)


def stop_adjustment():
    """停止自动调整"""
    global stop_event
    if stop_event:
        stop_event.set()
    btn_start.config(state=tk.NORMAL)
    btn_stop.config(state=tk.DISABLED)
    result_text.config(state=tk.NORMAL)
    result_text.insert(tk.END, "已停止自动调整\n")
    result_text.config(state=tk.DISABLED)


# 创建主窗口
style = Style(theme="flatly")
root = style.master
root.title("广告出价智能调整系统")
root.geometry("800x600")

# 顶部标题
header = ttk.Frame(root)
header.pack(pady=10)

ttk.Label(header, text="广告出价调整系统", font=("微软雅黑", 16, "bold")).pack()

# 输入区域
input_frame = ttk.LabelFrame(root, text="参数设置", padding=10)
input_frame.pack(fill=tk.X, padx=10, pady=5)

# 第一行
row1 = ttk.Frame(input_frame)
row1.pack(fill=tk.X, pady=5)

ttk.Label(row1, text="当前出价:", width=12).pack(side=tk.LEFT)
entry_current_bid = ttk.Entry(row1)
entry_current_bid.pack(side=tk.LEFT, expand=True, fill=tk.X, padx=5)

ttk.Label(row1, text="最大出价:", width=12).pack(side=tk.LEFT, padx=(10, 0))
entry_max_bid = ttk.Entry(row1)
entry_max_bid.pack(side=tk.LEFT, expand=True, fill=tk.X, padx=5)

# 第二行
row2 = ttk.Frame(input_frame)
row2.pack(fill=tk.X, pady=5)

ttk.Label(row2, text="最小出价:", width=12).pack(side=tk.LEFT)
entry_min_bid = ttk.Entry(row2)
entry_min_bid.pack(side=tk.LEFT, expand=True, fill=tk.X, padx=5)

ttk.Label(row2, text="总预算:", width=12).pack(side=tk.LEFT, padx=(10, 0))
entry_total_budget = ttk.Entry(row2)
entry_total_budget.pack(side=tk.LEFT, expand=True, fill=tk.X, padx=5)

# 第三行
row3 = ttk.Frame(input_frame)
row3.pack(fill=tk.X, pady=5)

ttk.Label(row3, text="当前累计消费:", width=12).pack(side=tk.LEFT)
entry_accumulated_spend = ttk.Entry(row3)
entry_accumulated_spend.pack(side=tk.LEFT, expand=True, fill=tk.X, padx=5)

btn_import = ttk.Button(row3, text="导入Excel", command=load_excel, width=12)
btn_import.pack(side=tk.LEFT, padx=10)

# 按钮区域
button_frame = ttk.Frame(root)
button_frame.pack(pady=10)

btn_start = ttk.Button(button_frame, text="启动自动调整", command=start_adjustment, style="success.TButton")
btn_start.pack(side=tk.LEFT, padx=5)

btn_stop = ttk.Button(button_frame, text="停止调整", command=stop_adjustment, style="danger.TButton", state=tk.DISABLED)
btn_stop.pack(side=tk.LEFT, padx=5)

# 结果显示区域
result_frame = ttk.LabelFrame(root, text="调整记录", padding=10)
result_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=5)

result_text = tk.Text(result_frame, wrap=tk.WORD, height=10)
result_text.pack(fill=tk.BOTH, expand=True)

scrollbar = ttk.Scrollbar(result_text)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
result_text.config(yscrollcommand=scrollbar.set)
scrollbar.config(command=result_text.yview)
result_text.config(state=tk.DISABLED)

# 状态栏
status_bar = ttk.Frame(root)
status_bar.pack(fill=tk.X, padx=10, pady=5)

ttk.Label(status_bar, text="就绪").pack(side=tk.LEFT)
ttk.Label(status_bar, text="开发: 您的团队", style="secondary.TLabel").pack(side=tk.RIGHT)

root.mainloop()